﻿var viewModel = new function () {
	//this.Checkdata = ko.observable(false);
	this.ColName = ko.observable("Username");
	this.SortOrder = ko.observable("desc");

	this.ReportList = ko.observableArray(data.ReportList);
	// No Results Found!
	this.NoResultsFound = ko.computed(function() {
		return (!this.ReportList() || !this.ReportList().length);
	}, this);

	this.PageSize = ko.observable(10);
	this.CurrentPageIndex = ko.observable(1);

	this.MaxPageIndex = ko.computed(function () {
		if (this.PageSize() != 0) {
			if (this.ReportList().length != 0) {
				return Math.ceil(ko.utils.unwrapObservable(this.ReportList().length / this.PageSize()));
			}
			else {
				this.CurrentPageIndex(0);
				return 0;
			}
		}
		else {
			return 0;
		}
	}, this);

	this.SourceId = ko.observable(0);
	this.SourceOptions = ko.observableArray(data.SourceFilter);

	this.UserId = ko.observable(0);
	this.UserOptions = ko.observableArray(data.UserFilter);

	this.DateRange = ko.observable(data.RangeFilter[7].ID);
	this.DateRangeOptions = ko.observableArray(data.RangeFilter);

	// Define varials to handle filter section
	this.RangeOption = ko.observable("true");
	this.FromDateEnable = ko.computed(function () {
		if (this.RangeOption() == "false")
			return true;

		return;
	}, this);
	this.RangeEnable = ko.computed(function () {
		if (this.RangeOption() == "true")
			return true;
		return;
	}, this);
	this.ToDateEnable = ko.computed(function () {
		if (this.RangeOption() == "false")
			return true;

		return;
	}, this);


	this.ItemOnPages = ko.computed(function () {
		var currentPage = this.CurrentPageIndex();
		var maxPage = this.MaxPageIndex();
		var pagevalue = this.PageSize().toString().replace(/\s/g, '');
		var PageSize = parseInt(pagevalue, 10);
		if (PageSize.toString() == 'NaN' || PageSize < 1 || PageSize > 100) {
			return "";
		}
		else {
			var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1);
			var endIndex = parseInt(startIndex) + parseInt(this.PageSize());

			return this.ReportList.slice(startIndex, endIndex);
		}
	}, this);

	this.search = function () {

		var dataPost = {
			"sourceId": $('#selectLead').editableSelect('value'),
			"userId": $('#selectUsers').editableSelect('value'),
			"checkRange": viewModel.RangeOption(),
			"range": viewModel.DateRange(),
			"startDate": $('#startDate').val(),
			"endDate": $('#endDate').val()
		};

		$("#visibleErrormsg").hide();
		openProcess();

		var urlPost = "/Reporting/GetMilestone";
		$.ajax({
			type: "POST",
			url: urlPost,
			data: dataPost,
			dataType: "json",
			success: function (returnData, textStatus, jqXHR) {
				hideProcess();

				if (typeof returnData != "undefined" && (typeof returnData.Error == "undefined" || !returnData.Error)) {
					// Success
					viewModel.ReportList(returnData);
					viewModel.CurrentPageIndex(1);
				}
				else {
					viewModel.ReportList([]);
					$("#visibleErrormsg").show();
				}
			},
			error: function (xhr, status, error) {
				hideProcess();

				viewModel.ReportList([]);
				showPopupError();
			}
		}); // End ajax post
		return false;
	}


	///////////////////// Paging /////////////////////////////
	this.PageSizeText = ko.computed(function () {

		var pagevalue = this.PageSize().toString().replace(/\s/g, '');
		var PageSize = parseInt(pagevalue, 10);
		this.CurrentPageIndex(1);
		if (!IsNumeric(pagevalue))
			return "* Xin hãy nhập một số giữa 1 - 100";
		else if (PageSize.toString() == 'NaN' || PageSize < 1 || PageSize > 100) {
		    return "* Xin hãy nhập một số giữa 1 - 100";
		}
		else {
			return "";
		}

	}, this);
	this.PageCurrentText = ko.computed(function () {
		var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, '');
		var pageindex = parseInt(pagevalue, 10);
		if (this.ReportList().length > 0) {
			if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "")
			    return "* Xin hãy nhập một số giữa 1 - " + this.MaxPageIndex() + " ";
			else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
			    return "* Xin hãy nhập một số giữa 1 - " + this.MaxPageIndex() + " ";
			}
			else {
				return "";
			}
		}
		else {
			return "";
		}

	}, this);

	this.PrevPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			this.CurrentPageIndex(page - 1);
		}
	}
	this.PrevButtonClass = ko.computed(function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			return "btn btn-prev-arrow prev-active";
		}
		else {
			return "btn btn-prev-arrow";
		}
	}, this);

	this.NextPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page < this.MaxPageIndex()) {
			this.CurrentPageIndex(page + 1);
		}
	}

	this.NextButtonClass = ko.computed(function () {
		if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
			return "btn btn-next-arrow next-disabled";
		else
			return "btn btn-next-arrow";
	}, this);

	function SwitchSortOrder() {
		if (viewModel.SortOrder() === "asc") {
			viewModel.SortOrder("desc");
		} else {
			viewModel.SortOrder("asc");
		}
	}

	function SetTHClass(event, colName) {
		RemoveSortIcons();

		if (viewModel.SortOrder() === "asc") {
			$("#" + colName).children("span").addClass("asc");
		} else {
			$("#" + colName).children("span").addClass("desc");
		}
	}

	function SetOrder(event, ColName) {

		if (this.ReportList().length > 0) {
			if (this.ColName() === ColName) {
				SwitchSortOrder();
			} else {
				this.ColName(ColName);
				this.SortOrder("desc");
			}

			SetTHClass(event, ColName);
			if (ColName != "") {
				this.ReportList(SortByPropertyName(ko.utils.unwrapObservable(this.ReportList()), ColName, this.SortOrder()));
			}
		}
	}
	this.SetOrder = SetOrder; // Set to an knockout object

	// sort all items
	function SortByPropertyName(items, propertyName, sortOrder) {
		return items.sort(sortProperty(propertyName, sortOrder));
	}
	function sortProperty(property, sortOrder) {
		if (sortOrder == "asc")
			return function (a, b) {
				var number = parseFloat(a[property].toString().toLowerCase());
				if (number != NaN && number > 0 && number.toString().length == a[property].toString().length)
					return (parseFloat(a[property].toString().toLowerCase()) < parseFloat(b[property].toString().toLowerCase())) ? -1 : (parseFloat(a[property].toString().toLowerCase()) > parseFloat(b[property].toString().toLowerCase())) ? 1 : 0;
				else
					return (a[property].toString().toLowerCase() < b[property].toString().toLowerCase()) ? -1 : (a[property].toString().toLowerCase() > b[property].toString().toLowerCase()) ? 1 : 0;
			}
		else
			return function (a, b) {
				var number = parseFloat(a[property].toString().toLowerCase());
				if (number != NaN && number > 0 && number.toString().length == a[property].toString().length)
					return (parseFloat(a[property].toString().toLowerCase()) > parseFloat(b[property].toString().toLowerCase())) ? -1 : (parseFloat(a[property].toString().toLowerCase()) < parseFloat(b[property].toString().toLowerCase())) ? 1 : 0;
				else
					return (a[property].toString().toLowerCase() > b[property].toString().toLowerCase()) ? -1 : (a[property].toString().toLowerCase() < b[property].toString().toLowerCase()) ? 1 : 0;
			}
	}

	function RemoveSortIcons() {
		$("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
		$("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");
	}
};
ko.applyBindings(viewModel, document.getElementById("main"));


// Check datetime
function isDateTime(a) {
	var a = new Date(a);
	return ($.isNumeric(a.getTime()));
}

$('body').ready(function () {
	$('#pageIndex').removeClass('text-active');
	$('#pageShow').removeClass('text-active');
	$('#pageIndex').focus(function () {
		$('#pageIndex').addClass('text-active');
	});
	$('#pageShow').focus(function () {
		$('#pageShow').addClass('text-active');
	});
	$('#pageIndex').blur(function () {
		setTimeout(function () {
			$('#pageIndex').removeClass('text-active');
		}, 1);
	});
	$('#pageShow').blur(function () {
		setTimeout(function () {
			$('#pageShow').removeClass('text-active');
		}, 1);
	});


	// Set CurrentDatetime for it
	$('#startDate').blur(function () {
		setTimeout(function () {
			if (!isDateUS($('#startDate').val())) {
				$('#startDate').val(getCurrentDate());
			}
		}, 1);
	});

	$('#endDate').blur(function () {
		setTimeout(function () {
			if (!isDateUS($('#endDate').val())) {
				$('#endDate').val(getCurrentDate());
			}
		}, 1);
	});
});

$(document).ready(function () {
	$('#selectLead').focus(function () {
		$(this).css("outline", "none");
	});
	$('#selectUsers').focus(function () {
		$(this).css("outline", "none");
	});
});